﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ingebet.Model;
using Ingebet.Model.Domain;
using Ingebet.Model.Enum;

namespace Ingebet.Web
{
    public partial class Parier : BasePage
    {
        private int? rencID;

        public int RencID
        {
            get
            {
                if (rencID == null)
                {
                    string val = Session["RencontreID"].ToString();
                    int id;
                    if (int.TryParse(val , out id))
                    {
                        rencID = id;
                    }
                }
                return rencID.Value;
            }
        }

        protected void Page_Load(object sender , EventArgs e)
        {
            if (!IsPostBack)
            {
                var ren = Global.Container.Resolve<RencontreModel>().GetByID(RencID);
                this.lblEquipe1.Text = ren.Equipe1.Nom;
                this.lblEquipe2.Text = ren.Equipe2.Nom;
                this.lblCote1.Text = ren.CoteMatch.CoteGain.ToString();
                this.lblCoteEgal.Text = ren.CoteMatch.CoteEgalite.ToString();
                this.lblCote2.Text = ren.CoteMatch.CotePerte.ToString();
            }
        }

        protected void btnEnregistrer_Click(object sender , EventArgs e)
        {
            int res;

            if (this.radioGain.Checked)
            {
                res = (int)EnumResultat.Gain;
            }
            else if (this.radioEgal.Checked)
            {
                res = (int)EnumResultat.Egalite;
            }
            else
            {
                res = (int)EnumResultat.Perte;
            }

            float montant;
            if (float.TryParse(this.txtMontant.Text , out montant) && this.txtMontant.Text != string.Empty)
            {
                var pari = new Pari()
                {
                    UtilID = this.UtilID ,
                    RencontreID = RencID ,
                    Resultat = res ,
                    MontantPari = montant ,
                    DatePari = DateTime.Now
                };

                Global.Container.Resolve<PariModel>().Insert(pari);
                var uti = Global.Container.Resolve<UtilisateurModel>().GetByID(UtilID);
                uti.Solde = uti.Solde - montant;
                Global.Container.Resolve<UtilisateurModel>().Update(uti);
                this.ClientScript.RegisterStartupScript(this.GetType() , "" , "window.close();" , true);
            }
            else
            {
                this.lblError.Text = "Montant nom valide";
            }
        }

        protected void btnFermer_Click(object sender , EventArgs e)
        {
            this.ClientScript.RegisterStartupScript(this.GetType() , "" , "window.close();" , true);
        }
    }
}